<template>
  <div>
    <div style="margin-bottom: 15px; text-align: right;">
      <el-tag type="info">
        <i class="el-icon-refresh" :class="{ 'is-rotating': isRefreshing }" style="margin-right: 5px;" />
        自动刷新倒计时: {{ countdown }}秒
      </el-tag>
    </div>
    <el-table :data="tableData" style="width: 100%" :header-cell-style="{ 'text-align': 'center' }">
      <el-table-column prop="id" label="ID" align="center" width="80" />
      <el-table-column label="专家头像" align="center" width="100">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.author_avatar"
            style="width: 50px; height: 50px; border-radius: 50%;"
            :src="scope.row.author_avatar"
            fit="cover"
          />
          <span v-else>无头像</span>
        </template>
      </el-table-column>
      <el-table-column prop="author_name" label="专家名称" align="center" />
      <el-table-column prop="live_name" label="直播名称" align="center" />
      <el-table-column label="直播间封面" align="center" width="300">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.live_image"
            style="width: 280px; height: 152px; border-radius: 4px;"
            :src="scope.row.live_image"
            fit="cover"
          />
          <span v-else>无封面</span>
        </template>
      </el-table-column>
      <el-table-column prop="roomId" label="房间ID" align="center" width="100" />
      <el-table-column label="是否正在直播" align="center" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success">是</el-tag>
          <el-tag v-else-if="scope.row.status === 0" type="info">否</el-tag>
          <el-tag v-else type="warning">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="初始点赞量" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.like || scope.row.like_count || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="600">
        <template slot-scope="scope">
          <el-button size="small" type="danger" @click="handleCloseRoom(scope.row)">关闭房间</el-button>
          <el-button size="small" type="primary" @click="handleUserManagement(scope.row)">用户管理</el-button>
          <el-button size="small" type="success" @click="handleSelectScheme(scope.row)">选择方案</el-button>
          <el-button size="small" type="warning" @click="handleSelectProduct(scope.row)">选择商品</el-button>
          <el-button size="small" type="info" @click="handleAddLikeCount(scope.row)">初始点赞</el-button>
          <el-button size="small" type="primary" plain @click="handleViewCart(scope.row)">查看小黄车</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 用户管理弹窗 -->
    <el-dialog title="用户管理" :visible.sync="userDialogVisible" width="80%">
      <div style="margin-bottom: 20px;">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户昵称"
          style="width: 300px;"
          @keyup.enter.native="searchUsers"
        >
          <el-button slot="append" icon="el-icon-search" @click="searchUsers" />
        </el-input>
      </div>
      <el-table :data="paginatedUserList" style="width: 100%" :header-cell-style="{ 'text-align': 'center' }">
        <el-table-column prop="userId" label="用户ID" align="center" width="100" />
        <el-table-column prop="nickname" label="昵称" align="center" />
        <el-table-column label="加入时间" align="center" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.joined_at) }}
          </template>
        </el-table-column>
        <el-table-column label="是否拉黑" align="center" width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.f_type === '2' || scope.row.f_type === 2" type="danger">已拉黑</el-tag>
            <el-tag v-else type="success">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否禁言" align="center" width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.j_type === '2' || scope.row.j_type === 2" type="warning">已禁言</el-tag>
            <el-tag v-else type="success">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              :type="(scope.row.f_type === '2' || scope.row.f_type === 2) ? 'success' : 'danger'"
              @click="handleBlockUser(scope.row)"
            >
              {{ (scope.row.f_type === '2' || scope.row.f_type === 2) ? '取消拉黑' : '拉黑用户' }}
            </el-button>
            <el-button
              size="mini"
              :type="(scope.row.j_type === '2' || scope.row.j_type === 2) ? 'success' : 'warning'"
              @click="handleMuteUser(scope.row)"
            >
              {{ (scope.row.j_type === '2' || scope.row.j_type === 2) ? '取消禁言' : '禁言用户' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tabListPage" style="margin-top: 20px;">
        <el-pagination
          :current-page="userCurrentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="userPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="userTotalCount"
          @size-change="handleUserSizeChange"
          @current-change="handleUserCurrentChange"
        />
      </div>
    </el-dialog>

    <!-- 方案选择弹窗 -->
    <SchemeSelector
      :visible.sync="schemeDialogVisible"
      :multiple="true"
      @confirm="handleSchemeSelect"
    />

    <!-- 商品选择弹窗 -->
    <ProductSelector
      :visible.sync="productDialogVisible"
      :multiple="true"
      @confirm="handleProductSelect"
    />

    <!-- 添加点赞数弹窗 -->
    <el-dialog title="添加点赞数" :visible.sync="likeCountDialogVisible" width="500px">
      <el-form :model="likeCountForm" label-width="120px">
        <el-form-item label="房间ID">
          <el-input v-model="likeCountForm.roomId" disabled />
        </el-form-item>

        <el-form-item label="添加点赞数" required>
          <el-input-number
            v-model="likeCountForm.addCount"
            :min="1"
            :max="999999"
            placeholder="请输入要添加的点赞数"
            style="width: 100%"
          />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="likeCountDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmLikeCount">确定</el-button>
      </div>
    </el-dialog>

    <!-- 查看小黄车弹窗 -->
    <el-dialog title="查看小黄车" :visible.sync="cartDialogVisible" width="80%">
      <el-tabs v-model="activeCartTab" @tab-click="handleCartTabClick">
        <el-tab-pane label="方案" name="scheme">
          <div class="cart-header">
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              :disabled="schemeList.length === 0 || cartLoading"
              @click="handleClearSchemes"
            >
              清空方案
            </el-button>
          </div>
          <div v-loading="cartLoading" class="cart-content">
            <div v-if="schemeList.length === 0" class="empty-cart">
              <i class="el-icon-box" style="font-size: 48px; color: #c0c4cc;" />
              <p>暂无方案</p>
            </div>
            <div v-else class="cart-list">
              <div v-for="(item, index) in schemeList" :key="index" class="cart-item">
                <div class="cart-item-avatar">
                  <el-image
                    v-if="item.expert_info && item.expert_info.avatar"
                    :src="item.expert_info.avatar"
                    fit="cover"
                    style="width: 60px; height: 60px; border-radius: 50%;"
                  />
                  <div v-else class="avatar-placeholder">
                    <i class="el-icon-user" />
                  </div>
                </div>
                <div class="cart-item-info">
                  <div class="cart-item-name">{{ item.title || '未命名方案' }}</div>
                  <div v-if="item.expert_info && item.expert_info.nickname" class="cart-item-expert">
                    <span>专家：{{ item.expert_info.nickname }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="商品" name="product">
          <div class="cart-header">
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              :disabled="productList.length === 0 || cartLoading"
              @click="handleClearProducts"
            >
              清空商品
            </el-button>
          </div>
          <div v-loading="cartLoading" class="cart-content">
            <div v-if="productList.length === 0" class="empty-cart">
              <i class="el-icon-box" style="font-size: 48px; color: #c0c4cc;" />
              <p>暂无商品</p>
            </div>
            <div v-else class="cart-list">
              <div v-for="(item, index) in productList" :key="index" class="cart-item">
                <div class="cart-item-avatar">
                  <el-image
                    v-if="item.main_image"
                    :src="item.main_image"
                    fit="cover"
                    style="width: 80px; height: 80px; border-radius: 4px;"
                  />
                  <div v-else class="avatar-placeholder product-placeholder">
                    <i class="el-icon-picture" />
                  </div>
                </div>
                <div class="cart-item-info">
                  <div class="cart-item-name">{{ item.name || '未命名商品' }}</div>
                  <div v-if="item.sku && item.sku.price" class="cart-item-price">
                    <span style="color: #e6a23c; font-weight: bold;">¥{{ item.sku.price }}</span>
                    <span v-if="item.sku.market_price && item.sku.market_price !== item.sku.price" style="color: #909399; text-decoration: line-through; margin-left: 10px;">
                      ¥{{ item.sku.market_price }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <div class="tabListPage">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size="PageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { getLiverList, closeLive, getLiveUserList, roomBlock, getLiveOtherList, saveLiveLike, saveLiveOther } from '../../../libs/api'
import SchemeSelector from '@/components/SchemeSelector/index.vue'
import ProductSelector from '@/components/ProductSelector/index.vue'

export default {
  components: {
    SchemeSelector,
    ProductSelector
  },
  data() {
    return {
      tableData: [],
      currentPage: 1,
      PageSize: 10,
      totalCount: 1,
      pageSizes: [5, 10, 20],
      // 用户管理弹窗相关
      userDialogVisible: false,
      userList: [],
      userCurrentPage: 1,
      userPageSize: 10,
      userTotalCount: 0,
      searchKeyword: '',
      currentRoomId: null,
      currentUserId: null,
      // 自动刷新相关
      refreshTimer: null,
      countdownTimer: null,
      countdown: 5,
      isRefreshing: false,
      // 方案和商品选择相关
      schemeDialogVisible: false,
      productDialogVisible: false,
      currentRow: null,
      selectedSchemes: [],
      selectedProducts: [],
      // 点赞数相关
      likeCountDialogVisible: false,
      likeCountForm: {
        roomId: '',
        currentLikeCount: 0,
        addCount: 1
      },
      // 小黄车相关
      cartDialogVisible: false,
      activeCartTab: 'scheme',
      cartLoading: false,
      schemeList: [],
      productList: [],
      currentCartRoomId: null
    }
  },
  computed: {
    // 分页后的用户列表
    paginatedUserList() {
      const start = (this.userCurrentPage - 1) * this.userPageSize
      const end = start + this.userPageSize
      return this.userList.slice(start, end)
    }
  },
  created() {
    this.getLiveRoomList()
    this.startAutoRefresh()
  },
  beforeDestroy() {
    this.stopAutoRefresh()
  },
  methods: {
    // 获取直播房间列表
    getLiveRoomList() {
      this.isRefreshing = true
      getLiverList({
        page: this.currentPage,
        limit: this.PageSize
      }).then(res => {
        console.log(res)
        // API返回的data是数组，不是对象
        if (Array.isArray(res.data)) {
          this.tableData = res.data || []
          this.totalCount = res.data.length || 0
        } else {
          // 兼容其他可能的返回格式
          this.tableData = res.data.data || res.data.list || []
          this.totalCount = res.data.total || res.data.length || 0
        }
      }).catch(err => {
        console.error('获取直播房间列表失败:', err)
        this.$message.error('获取直播房间列表失败')
      }).finally(() => {
        this.isRefreshing = false
      })
    },
    // 开始自动刷新
    startAutoRefresh() {
      this.countdown = 5
      // 倒计时定时器
      this.countdownTimer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          this.countdown = 5
          this.getLiveRoomList()
        }
      }, 1000)
    },
    // 停止自动刷新
    stopAutoRefresh() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
        this.countdownTimer = null
      }
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer)
        this.refreshTimer = null
      }
    },
    // 关闭房间
    handleCloseRoom(row) {
      this.$confirm('确定要关闭该直播房间吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.status === 1) {
          closeLive({
            roomId: row.roomId.toString()
          }).then(res => {
            this.$message.success('房间已关闭')
            this.countdown = 5 // 重置倒计时
            this.getLiveRoomList()
          }).catch(err => {
            console.error('关闭房间失败:', err)
            this.$message.error('关闭房间失败')
          })
        } else {
          this.$message.warning('该房间未在直播中')
        }
      }).catch(() => {
        this.$message.info('已取消关闭')
      })
    },
    // 用户管理
    handleUserManagement(row) {
      this.currentRoomId = row.roomId
      this.currentUserId = row.id
      this.userDialogVisible = true
      this.userCurrentPage = 1
      this.searchKeyword = ''
      this.getRoomUserList()
    },
    // 获取房间用户列表
    getRoomUserList() {
      if (!this.currentRoomId) {
        this.$message.warning('房间ID不存在')
        return
      }
      getLiveUserList({
        roomId: this.currentRoomId.toString(),
        nickname: this.searchKeyword,
        page: this.userCurrentPage
      }).then(res => {
        console.log(res)
        // API返回的数据结构：data.users 是用户数组
        if (res.data && res.data.users) {
          const users = res.data.users || []
          // 如果有搜索关键词，进行本地过滤（只搜索nickname字段）

          this.userList = users
          this.userTotalCount = users.length
        } else {
          this.userList = []
          this.userTotalCount = 0
        }
      }).catch(err => {
        console.error('获取用户列表失败:', err)
        this.$message.error('获取用户列表失败')
      })
    },
    // 搜索用户
    searchUsers() {
      this.userCurrentPage = 1
      this.getRoomUserList()
    },
    // 拉黑用户
    handleBlockUser(row) {
      const isBlocked = row.f_type === '2' || row.f_type === 2
      const action = isBlocked ? '取消拉黑' : '拉黑'
      this.$confirm(`确定要${action}该用户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // f_type: 1=正常, 2=拉黑
        const blockStatus = isBlocked ? 1 : 2
        roomBlock({
          roomId: this.currentRoomId.toString(),
          user_id: row.userId.toString(),
          f_type: blockStatus.toString(),
          j_type: row.j_type ? row.j_type.toString() : '1'
        }).then(res => {
          this.$message.success(`${action}成功`)
          // 更新本地数据
          row.f_type = blockStatus.toString()
          // 或者重新获取列表
          // this.getRoomUserList()
        }).catch(err => {
          console.error(`${action}失败:`, err)
          this.$message.error(`${action}失败`)
        })
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },
    // 禁言用户
    handleMuteUser(row) {
      const isMuted = row.j_type === '2' || row.j_type === 2
      const action = isMuted ? '取消禁言' : '禁言'
      this.$confirm(`确定要${action}该用户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // j_type: 1=正常, 2=禁言
        const muteStatus = isMuted ? 1 : 2
        roomBlock({
          roomId: this.currentRoomId.toString(),
          user_id: row.userId.toString(),
          f_type: row.f_type ? row.f_type.toString() : '1',
          j_type: muteStatus.toString()
        }).then(res => {
          this.$message.success(`${action}成功`)
          row.j_type = muteStatus.toString()
        }).catch(err => {
          console.error(`${action}失败:`, err)
          this.$message.error(`${action}失败`)
        })
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },
    // 分页相关
    handleCurrentChange(val) {
      this.currentPage = val
      this.countdown = 5 // 重置倒计时
      this.getLiveRoomList()
    },
    handleSizeChange(val) {
      this.PageSize = val
      this.currentPage = 1
      this.countdown = 5 // 重置倒计时
      this.getLiveRoomList()
    },
    // 用户列表分页
    handleUserCurrentChange(val) {
      this.userCurrentPage = val
    },
    handleUserSizeChange(val) {
      this.userPageSize = val
      this.userCurrentPage = 1
    },
    // 格式化时间戳
    formatTime(timestamp) {
      if (!timestamp) return '-'
      const date = new Date(timestamp * 1000)
      const Y = date.getFullYear() + '-'
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
      const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return Y + M + D + h + m + s
    },
    // 选择方案
    handleSelectScheme(row) {
      this.currentRow = row
      this.schemeDialogVisible = true
    },
    // 方案选择确认
    handleSchemeSelect(schemes) {
      console.log('选择的方案:', schemes)
      this.selectedSchemes = schemes
      if (this.currentRow) {
        // 保存房间ID，避免异步回调中访问null
        const roomId = this.currentRow.roomId
        const roomIdStr = roomId.toString()
        // 将方案ID数组转换为逗号分隔的字符串，如果为空则传空字符串（清空）
        const schemeIds = schemes.length > 0 ? schemes.map(s => s.id).join(',') : ''
        // 清空currentRow，避免重复操作
        this.currentRow = null
        // 调用API保存方案关联关系（空选时清空）
        saveLiveOther({
          room_id: roomIdStr,
          type: '1', // 1表示方案
          ids: schemeIds
        }).then(res => {
          if (res && res.code === 1) {
            if (schemes.length > 0) {
              this.$message.success(`成功为房间 ${roomId} 添加 ${schemes.length} 个方案`)
            } else {
              this.$message.success(`成功清空房间 ${roomId} 的方案`)
            }
            // 刷新列表
            this.getLiveRoomList()
          } else {
            this.$message.error(res.msg || '保存方案失败')
          }
        }).catch(err => {
          console.error('保存方案失败:', err)
          this.$message.error('保存方案失败')
        })
      } else {
        this.currentRow = null
      }
    },
    // 选择商品
    handleSelectProduct(row) {
      this.currentRow = row
      this.productDialogVisible = true
    },
    // 商品选择确认
    handleProductSelect(products) {
      console.log('选择的商品:', products)
      this.selectedProducts = products
      if (this.currentRow) {
        // 保存房间ID，避免异步回调中访问null
        const roomId = this.currentRow.roomId
        const roomIdStr = roomId.toString()
        // 将商品ID数组转换为逗号分隔的字符串，如果为空则传空字符串（清空）
        const productIds = products.length > 0 ? products.map(p => p.id).join(',') : ''
        // 清空currentRow，避免重复操作
        this.currentRow = null
        // 调用API保存商品关联关系（空选时清空）
        saveLiveOther({
          room_id: roomIdStr,
          type: '2', // 2表示商品
          ids: productIds
        }).then(res => {
          if (res && res.code === 1) {
            if (products.length > 0) {
              this.$message.success(`成功为房间 ${roomId} 添加 ${products.length} 个商品`)
            } else {
              this.$message.success(`成功清空房间 ${roomId} 的商品`)
            }
            // 刷新列表
            this.getLiveRoomList()
          } else {
            this.$message.error(res.msg || '保存商品失败')
          }
        }).catch(err => {
          console.error('保存商品失败:', err)
          this.$message.error('保存商品失败')
        })
      } else {
        this.currentRow = null
      }
    },
    // 添加点赞数
    handleAddLikeCount(row) {
      this.currentRow = row
      this.likeCountForm = {
        roomId: row.roomId || '',
        currentLikeCount: row.like || row.like_count || row.likeCount || 0,
        addCount: 1
      }
      this.likeCountDialogVisible = true
    },
    // 确认添加点赞数
    handleConfirmLikeCount() {
      if (!this.likeCountForm.addCount || this.likeCountForm.addCount <= 0) {
        this.$message.warning('请输入有效的点赞数')
        return
      }

      // 计算新的点赞数
      const currentLike = this.likeCountForm.currentLikeCount || 0
      const newLike = currentLike + this.likeCountForm.addCount

      // 调用API保存点赞数
      saveLiveLike({
        room_id: this.likeCountForm.roomId.toString(),
        like: newLike.toString()
      }).then(res => {
        if (res && res.code === 1) {
          this.$message.success(`成功设置点赞数为 ${newLike}`)
          this.likeCountDialogVisible = false
          // 更新本地数据
          if (this.currentRow) {
            this.currentRow.like = newLike
            this.currentRow.like_count = newLike
            this.currentRow.likeCount = newLike
          }
          // 刷新列表
          this.getLiveRoomList()
        } else {
          this.$message.error(res.msg || '保存点赞数失败')
        }
        this.currentRow = null
      }).catch(err => {
        console.error('保存点赞数失败:', err)
        this.$message.error('保存点赞数失败')
        this.currentRow = null
      })
    },
    // 查看小黄车
    handleViewCart(row) {
      this.currentCartRoomId = row.roomId
      this.cartDialogVisible = true
      this.activeCartTab = 'scheme'
      this.schemeList = []
      this.productList = []
      // 默认加载方案列表
      this.loadCartData('scheme')
    },
    // 切换标签页
    handleCartTabClick(tab) {
      if (tab.name === 'scheme' && this.schemeList.length === 0) {
        this.loadCartData('scheme')
      } else if (tab.name === 'product' && this.productList.length === 0) {
        this.loadCartData('product')
      }
    },
    // 加载小黄车数据
    loadCartData(type) {
      if (!this.currentCartRoomId) {
        this.$message.warning('房间ID不存在')
        return
      }
      this.cartLoading = true
      const params = {
        room_id: this.currentCartRoomId.toString(),
        type: type === 'scheme' ? '1' : '2'
      }
      getLiveOtherList(params).then(res => {
        if (res && res.data) {
          const data = res.data.list || res.data || []
          if (type === 'scheme') {
            this.schemeList = data
          } else {
            this.productList = data
          }
        } else {
          if (type === 'scheme') {
            this.schemeList = []
          } else {
            this.productList = []
          }
        }
        this.cartLoading = false
      }).catch(err => {
        console.error('获取小黄车数据失败:', err)
        this.$message.error('获取小黄车数据失败')
        if (type === 'scheme') {
          this.schemeList = []
        } else {
          this.productList = []
        }
        this.cartLoading = false
      })
    },
    // 清空方案
    handleClearSchemes() {
      if (!this.currentCartRoomId) {
        this.$message.warning('房间ID不存在')
        return
      }
      this.$confirm('确定要清空该房间的所有方案吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const roomIdStr = this.currentCartRoomId.toString()
        saveLiveOther({
          room_id: roomIdStr,
          type: '1', // 1表示方案
          ids: '' // 空字符串表示清空
        }).then(res => {
          if (res && res.code === 1) {
            this.$message.success('成功清空方案')
            // 重新加载方案列表
            this.loadCartData('scheme')
            // 刷新主列表
            this.getLiveRoomList()
          } else {
            this.$message.error(res.msg || '清空方案失败')
          }
        }).catch(err => {
          console.error('清空方案失败:', err)
          this.$message.error('清空方案失败')
        })
      }).catch(() => {
        this.$message.info('已取消清空')
      })
    },
    // 清空商品
    handleClearProducts() {
      if (!this.currentCartRoomId) {
        this.$message.warning('房间ID不存在')
        return
      }
      this.$confirm('确定要清空该房间的所有商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const roomIdStr = this.currentCartRoomId.toString()
        saveLiveOther({
          room_id: roomIdStr,
          type: '2', // 2表示商品
          ids: '' // 空字符串表示清空
        }).then(res => {
          if (res && res.code === 1) {
            this.$message.success('成功清空商品')
            // 重新加载商品列表
            this.loadCartData('product')
            // 刷新主列表
            this.getLiveRoomList()
          } else {
            this.$message.error(res.msg || '清空商品失败')
          }
        }).catch(err => {
          console.error('清空商品失败:', err)
          this.$message.error('清空商品失败')
        })
      }).catch(() => {
        this.$message.info('已取消清空')
      })
    }
  }
}
</script>

<style scoped>
.tabListPage {
  margin-top: 30px;
  text-align: right;
}

.is-rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 小黄车样式 */
.cart-header {
  margin-bottom: 15px;
  text-align: right;
}

.cart-content {
  min-height: 300px;
  padding: 20px;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-cart p {
  margin-top: 20px;
  font-size: 14px;
}

.cart-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fff;
  transition: all 0.3s;
}

.cart-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.cart-item-avatar {
  margin-right: 15px;
  flex-shrink: 0;
}

.avatar-placeholder {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  font-size: 24px;
}

.avatar-placeholder.product-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 4px;
}

.cart-item-info {
  flex: 1;
  min-width: 0;
}

.cart-item-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cart-item-expert {
  font-size: 14px;
  color: #606266;
}

.cart-item-price {
  font-size: 14px;
  margin-top: 5px;
}
</style>
